package antonTest;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;


public class Nest extends JPanel
{
	private Timer timer;
	private ArrayList<Scent> scents;
	private Random random;
	private long time = 0;
	
	public Nest() {
		scents = new ArrayList<Scent>();
		random = new Random();
		
		timer = new Timer(10, new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
//				if(Nest.this.getWidth() < 1 || Nest.this.getHeight() < 1)
//				{
//					for (int i = 0; i < 10; i++) {
//						scents.add(new Scent(50, new Point(random.nextInt(200), random.nextInt(200))));
//					}
//				}
//				else
//				{
//					for (int i = 0; i < 10; i++) {
//						scents.add(new Scent(50, new Point(random.nextInt(Nest.this.getWidth()), random.nextInt(Nest.this.getHeight()))));
//					}
//				}
				
				Nest.this.repaint();
			}});
		
		timer.start();
	}
	
	private AlphaComposite makeComposite(float alpha) {
	    int type = AlphaComposite.SRC_OVER;
	    return(AlphaComposite.getInstance(type, alpha));
	  }

	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		for (int i = 0; i < 50; i++) {
			Scent s = new Scent(50, new Point(random.nextInt(Nest.this.getWidth()), random.nextInt(Nest.this.getHeight())));
			s.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
			scents.add(s);
		}
		
		Graphics2D g2d = (Graphics2D) g.create();
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		
		for (int i = scents.size() - 1; i >= 0; i--) {
			Scent scent = scents.get(i);
			scent.HappyBirthday();
			
			if (scent.isAlive()) {
//				System.out.println(scent.getAge()+ " / "+scent.getLifetime());
				
				int lifeTime = scent.getLifetime()/2;
				int age = scent.getAge();
				
				if ((float) age / (float) lifeTime < 1) {
					g2d.setComposite(this.makeComposite((float) age / (float) lifeTime));
				}
				else {
					age = age - lifeTime;
					
					g2d.setComposite(this.makeComposite(1-(float) age / (float) lifeTime));
				}
				
				g2d.setColor(scent.getColor());
				g2d.fillOval((int)scent.getPosition().getX(),(int)scent.getPosition().getY(), 20, 20);
			}
			else {
//				System.out.print(".");
				scents.remove(i);
			}
		}
		
//		System.out.println("");
		
		long t = System.currentTimeMillis() - time;
		time = System.currentTimeMillis();
		System.out.println(t + " -> " + scents.size());
		
	}
}










